package com.zhuqi.handler;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.zhuqi.domain.ChatMessageDo;
import com.zhuqi.proto.ChatMessage;
import com.zhuqi.proto.build.ChatMessageBuild;
import com.zhuqi.proto.cost.MessageProtocolBufEnum;
import com.zhuqi.service.session.Session;
import com.zhuqi.session.messge.MessagePackage;
import com.zhuqi.util.SpringBeanUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Date;

/**
 * @author ZhuQi
 * @ClassName ChatRequestMessageHandler
 * @Date 2023/1/16 17:03
 * @Version 1.0
 * @Description 单聊消息发送
 */
@Slf4j
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatMessage.ChatMessageRequest> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ChatMessage.ChatMessageRequest msg) {
		String content = msg.getContent();
		String from = msg.getFrom();
		String to = msg.getTo();
		Session session = SpringBeanUtil.getBean(Session.class);
		StringRedisTemplate stringRedisTemplate = SpringBeanUtil.getBean(StringRedisTemplate.class);
		// 获取接收人的 Channel
		Channel channel = session.getChannel(to);
		ChatMessage.ChatMessageResponse chatResponseMessage;
		MessagePackage messagePackage = new MessagePackage();

		sendMessageToSaveData(content, from, to, stringRedisTemplate);

		if (ObjectUtil.isEmpty(channel)) {
			// 用户下线消息发送给自己
			log.info("单发消息用户已下线，用户名：{}", to);
			chatResponseMessage = ChatMessageBuild.createChatResponseMessage(from, to, "失败，该用户已下线");
			messagePackage.setData(chatResponseMessage.toByteArray());
			messagePackage.setBusinessCode(MessageProtocolBufEnum.CHAT_RESPONSE_MESSAGE.getCode());
			ctx.writeAndFlush(messagePackage);
			return;
		} else {
			chatResponseMessage = ChatMessageBuild.createChatResponseMessage(from, to, content);
			messagePackage.setData(chatResponseMessage.toByteArray());
			messagePackage.setBusinessCode(MessageProtocolBufEnum.CHAT_RESPONSE_MESSAGE.getCode());
		}
		channel.writeAndFlush(messagePackage);
	}

	/**
	 * 发送消息异步保存数据
	 * @param content 内容
	 * @param from 发送人
	 * @param to 接收人
	 * @param stringRedisTemplate redis
	 */
	private static void sendMessageToSaveData(String content, String from, String to, StringRedisTemplate stringRedisTemplate) {
		ChatMessageDo chatMessageDo = new ChatMessageDo();
		chatMessageDo.setContent(content);
		chatMessageDo.setFromUserName(from);
		chatMessageDo.setToUserName(to);
		chatMessageDo.setCreateTime(new Date());
		chatMessageDo.setIsDeleted(0);
		stringRedisTemplate.convertAndSend("chat",JSON.toJSONString(chatMessageDo) );
	}


}
